package com.yihen.controller;

import com.yihen.dto.Result;
import com.yihen.service.impl.QiniuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/uploadImg")
@Slf4j
/*
*   上传头像
* */
public class QiniuController {

    @Autowired
    private QiniuService qiniuService;


    @PostMapping
    @PermitAll
    public Result uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Result result = new Result();

        if(file.isEmpty()) {

            result.setMessage("图片为空，请重新上传");
            return result;
        }

        try {
            String fileUrl=qiniuService.saveImage(file);

            result.setFlag(true);
            result.setMessage("图片上传成功");
            result.setData("http://"+fileUrl);

            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        result.setMessage("图片上传发生异常！");
        return result;
    }
}

